package com.huo.utils;

import java.util.Random;

/**
 * @Description: 随机生成验证码工具类
 * @Author: 汪青松
 * @CreateDate: 2021/2/7 22:17
 */
public class ValidateCodeUtils {

    /**
     * @Description: 随机生成4位或者6位的验证码
     * @Author: 汪青松
     * @Param: [length]
     * @Return: java.lang.Integer
     * @CreateDate: 2021/2/7 22:22
     */
    public static Integer generateValidateCode(int length) {
        Integer code = null;
        if (length == 4) {
            code = new Random().nextInt(9999);
            if (code < 1000) {
                code += 1000;
            }
        } else if (length == 6) {
            code = new Random().nextInt(999999);
            if (code < 100000) {
                code += 100000;
            }
        } else {
            throw new RuntimeException("只能生成4位或者6位的数字验证码");
        }
        return code;
    }

    /**
     * @Description: 随机生成指定长度字符串验证码
     * @Author: 汪青松
     * @Param: [length]
     * @Return: java.lang.String
     * @CreateDate: 2021/2/8 21:28
     */
    public static String generateCodeForString(int length) {
        Random random = new Random();
        String str = Integer.toHexString(random.nextInt());
        return str.substring(0, length);
    }
}
